package com.qijin.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class HttpUtil {


    final static DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 生成待签名串
     */
    public static String genSignData(JSONObject jsonObject) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(jsonObject.keySet());
        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if ("sign".equals(key)) {
                continue;
            }
            String value = jsonObject.getString(key);
            if ("".equals(value) || value == null) {
                continue;
            }
            content.append((i == 0 ? "" : "&") + key + "=" + value);
        }
        String signSrc = content.toString();
        if (signSrc.startsWith("&")) {
            signSrc = signSrc.replaceFirst("&", "");
        }
        return signSrc;
    }

    public static String doPost(String url, JSONObject json, String charset) {
        return doPost(url, json.toJSONString(), charset);
    }

    public static String doPost(String url, String jsonStr, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            // System.out.println(jsonStr);
            // 设置参数
            StringEntity s = new StringEntity(jsonStr,"utf-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json;charset=utf-8");
            httpPost.setEntity(s);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
                // System.out.println("response body:" + result);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public String getTimeStamp() {
        return df.format(new Date());
    }
}
